package com.fakeDYChat.common.common.exception;

import com.fakeDYChat.common.common.domain.vo.resp.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 参数校验异常处理
     *
     * @param e 参数校验异常
     * @return com.fakeDYChat.common.common.domain.vo.resp.ApiResult<java.lang.Void>
     * @author Tang
     * @date 2023/12/30 17:26
     **/
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ApiResult<Void> handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(x -> {
            sb.append(x.getField()).append(x.getDefaultMessage()).append(",");
        });
        String message = sb.toString();
        return ApiResult.fail(CommonErrorEnum.PARAM_INVALID.getErrorCode(), message.substring(0, message.length() - 1));
    }

    @ExceptionHandler(value = BusinessException.class)
    public ApiResult<Void> handlerBusinessException(BusinessException e) {
        return ApiResult.fail(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 未知异常
     *
     * @param e 异常
     * @return com.fakeDYChat.common.common.domain.vo.resp.ApiResult<java.lang.Void>
     * @author Tang
     * @date 2023/12/30 17:27
     **/
    @ExceptionHandler(value = Throwable.class)
    public ApiResult<Void> handlerThrowable(Throwable e) {
        log.error("System error,the reason is {}", e.getMessage(), e);
        return ApiResult.fail(CommonErrorEnum.SYSTEM_ERROR);
    }
}
